<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="报关单号" prop="declarationNo">
        <el-input
          v-model="queryParams.declarationNo"
          placeholder="请输入报关单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预录入编号" prop="preEntryNo">
        <el-input
          v-model="queryParams.preEntryNo"
          placeholder="请输入预录入编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="贸易方式" prop="tradeMode">
        <el-select v-model="queryParams.tradeMode" placeholder="请选择贸易方式" clearable>
          <el-option
            v-for="dict in dict.type.fiscale_trade_mode"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="当前状态" prop="customsStatus">
        <el-select v-model="queryParams.customsStatus" placeholder="请选择当前状态" clearable>
          <el-option
            v-for="dict in dict.type.fiscale_customs_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申报日期" prop="submitDate">
        <el-date-picker clearable
          v-model="queryParams.submitDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-refresh"
          size="mini"
          :disabled="multiple"
          @click="handleBatchRefresh"
          v-hasPermi="['fiscale:declaration:queryStatus']"
        >手动刷新状态</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDownload"
          v-hasPermi="['fiscale:declaration:downloadClearance']"
        >批量下载结关单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="declarationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="报关单号" align="center" prop="declarationNo" />
      <el-table-column label="预录入编号" align="center" prop="preEntryNo" />
      <el-table-column label="申报日期" align="center" prop="submitDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.submitDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报关类型" align="center" prop="declarationType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_declaration_type" :value="scope.row.declarationType"/>
        </template>
      </el-table-column>
      <el-table-column label="贸易方式" align="center" prop="tradeMode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_trade_mode" :value="scope.row.tradeMode"/>
        </template>
      </el-table-column>
      <el-table-column label="运输方式" align="center" prop="transportMode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_transport_mode" :value="scope.row.transportMode"/>
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="center" prop="totalAmount">
        <template slot-scope="scope">
          <span>{{ scope.row.totalAmount }} {{ scope.row.currency }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前状态" align="center" prop="customsStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.fiscale_customs_status" :value="scope.row.customsStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="最后查询时间" align="center" prop="lastStatusQueryTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastStatusQueryTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleRefreshStatus(scope.row)"
            v-hasPermi="['fiscale:declaration:queryStatus']"
          >刷新状态</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewReceipt(scope.row)"
            v-hasPermi="['fiscale:declaration:viewReceipt']"
          >查看回执</el-button>
          <el-button
            v-if="scope.row.customsStatus === 'cleared'"
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownloadClearance(scope.row)"
            v-hasPermi="['fiscale:declaration:downloadClearance']"
          >下载结关单</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-time"
            @click="handleViewHistory(scope.row)"
            v-hasPermi="['fiscale:declaration:tracking']"
          >状态历史</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看回执对话框 -->
    <el-dialog title="海关回执详情" :visible.sync="receiptVisible" width="800px" append-to-body>
      <div v-if="receiptData">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="友好格式" name="friendly">
            <el-descriptions title="回执信息" :column="2" border>
              <el-descriptions-item label="预录入编号">{{ receiptData.preEntryNo }}</el-descriptions-item>
              <el-descriptions-item label="申报状态">{{ receiptData.status }}</el-descriptions-item>
              <el-descriptions-item label="回执时间">{{ receiptData.receiptTime }}</el-descriptions-item>
              <el-descriptions-item label="海关消息">{{ receiptData.message }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
          <el-tab-pane label="原始报文" name="raw">
            <el-input
              type="textarea"
              :rows="15"
              v-model="receiptData.rawData"
              readonly
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 状态历史对话框 -->
    <el-dialog title="状态变更历史" :visible.sync="historyVisible" width="600px" append-to-body>
      <el-timeline>
        <el-timeline-item
          v-for="item in statusHistory"
          :key="item.logId"
          :timestamp="item.statusTime"
          placement="top"
          :type="getTimelineType(item.newStatus)"
        >
          <el-card>
            <h4>{{ getStatusLabel(item.newStatus) }}</h4>
            <p v-if="item.customsMessage">{{ item.customsMessage }}</p>
            <p style="color: #909399; font-size: 12px;">
              操作类型: {{ item.operationType === 'auto' ? '自动' : '手动' }}
              <span v-if="item.operator"> | 操作员: {{ item.operator }}</span>
            </p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
import { 
  listTracking, 
  refreshStatus, 
  batchRefreshStatus, 
  getCustomsReceipt, 
  downloadClearanceDocument, 
  getStatusHistory 
} from "@/api/fiscale/declarationTracking";

export default {
  name: "DeclarationTracking",
  dicts: ['fiscale_declaration_type', 'fiscale_trade_mode', 'fiscale_transport_mode', 'fiscale_customs_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报关单列表
      declarationList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        declarationNo: null,
        preEntryNo: null,
        tradeMode: null,
        customsStatus: null,
        submitDate: null,
      },
      // 回执对话框
      receiptVisible: false,
      receiptData: null,
      activeTab: 'friendly',
      // 状态历史对话框
      historyVisible: false,
      statusHistory: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询报关单跟踪列表 */
    getList() {
      this.loading = true;
      listTracking(this.queryParams).then(response => {
        this.declarationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.declarationId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 刷新单个报关单状态 */
    handleRefreshStatus(row) {
      const declarationId = row.declarationId;
      this.$modal.confirm('确认刷新报关单"' + row.declarationNo + '"的状态？').then(function() {
        return refreshStatus(declarationId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("状态刷新成功");
      }).catch(() => {});
    },

    /** 批量刷新状态 */
    handleBatchRefresh() {
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要刷新状态的报关单");
        return;
      }
      
      this.$modal.confirm('确认刷新选中的 ' + this.ids.length + ' 个报关单的状态？').then(() => {
        const params = { declarationIds: this.ids };
        batchRefreshStatus(params).then(() => {
          this.getList();
          this.$modal.msgSuccess("批量刷新成功");
        });
      }).catch(() => {});
    },

    /** 查看回执 */
    handleViewReceipt(row) {
      getCustomsReceipt(row.declarationId).then(response => {
        this.receiptData = response.data;
        this.receiptVisible = true;
        this.activeTab = 'friendly';
      });
    },

    /** 下载结关单 */
    handleDownloadClearance(row) {
      downloadClearanceDocument(row.declarationId).then(response => {
        if (response.code === 200) {
          const fileUrl = response.data.fileUrl;
          const fileName = response.data.fileName || '结关单.pdf';
          
          // 创建下载链接
          const link = document.createElement('a');
          link.href = fileUrl;
          link.download = fileName;
          link.click();
          
          this.$modal.msgSuccess("结关单下载成功");
        } else {
          this.$modal.msgError("下载失败：" + response.msg);
        }
      });
    },

    /** 批量下载结关单 */
    handleBatchDownload() {
      const clearedDeclarations = this.declarationList.filter(item => 
        this.ids.includes(item.declarationId) && item.customsStatus === 'cleared'
      );
      
      if (clearedDeclarations.length === 0) {
        this.$modal.msgError("请选择已结关的报关单");
        return;
      }

      this.$modal.confirm('确认下载选中的 ' + clearedDeclarations.length + ' 个结关单？').then(() => {
        clearedDeclarations.forEach(declaration => {
          this.handleDownloadClearance(declaration);
        });
      }).catch(() => {});
    },

    /** 查看状态历史 */
    handleViewHistory(row) {
      getStatusHistory(row.declarationId).then(response => {
        this.statusHistory = response.data;
        this.historyVisible = true;
      });
    },

    /** 获取时间轴类型 */
    getTimelineType(status) {
      const typeMap = {
        'draft': 'info',
        'submitted': 'primary',
        'inspecting': 'warning',
        'approved': 'success',
        'released': 'success',
        'cleared': 'success',
        'rejected': 'danger',
        'exception': 'danger'
      };
      return typeMap[status] || 'info';
    },

    /** 获取状态标签 */
    getStatusLabel(status) {
      const statusMap = {
        'draft': '草稿',
        'submitted': '已申报',
        'inspecting': '查验中',
        'approved': '已审批',
        'released': '已放行',
        'cleared': '已结关',
        'rejected': '已拒绝',
        'exception': '异常'
      };
      return statusMap[status] || status;
    }
  }
};
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>